package com.example.wyh.intelcheckbash;

import android.app.ActionBar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.ParcelUuid;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.BoringLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.bluetoothchat.BluetoothChatFragment;
import com.example.wyh.intelcheckbash.common.CommonUtil;
import com.example.wyh.intelcheckbash.common.SysExitUtil;
import com.example.wyh.intelcheckbash.task.CheckDefectActivity;
import com.example.wyh.intelcheckbash.task.UploadCheckedTaskActivity;

import org.json.JSONArray;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;

import static android.R.id.candidatesArea;
import static android.R.id.list;

/**
 * Created by chen on 17/9/20.
 */

public class SeismicActivity extends AppCompatActivity {

    private Boolean isOnMeasureSeismic = false;

    BluetoothChatFragment mFragment = MainActivity.getInstance();
    Handler handler = new Handler();
    private String mStrMetricalType;//加速度 速度 位移 选择测量类型

    private EditText mEditEffectiveValue;
    private EditText mPeakPeakValue;
    private EditText mPeakPeakValueMM;
    private EditText mPeakValue;
    RelativeLayout spectrum_speed_chart;
    RelativeLayout spectrum_add_speed_chart;
    RelativeLayout spectrum_drift_chart;
    LinearLayout spectrum_speed;
    LinearLayout spectrum_add_speed;
    LinearLayout spectrum_drift;
    RelativeLayout speed_btn;
    RelativeLayout add_speed_btn;
    RelativeLayout drift_btn;

    ArrayList mArrRateList;
    ArrayList mPointNumber;

    Date mSendOKDateTime = null;

    double[] mArrOneTestAData = new double[85];
    double[] mArrOneTestVData = new double[85];
    double[] mArrOneTestDData = new double[85];

    double[] mArrAllItemAData = new double[0];
    double[] mArrAllItemVData = new double[0];
    double[] mArrAllItemDData = new double[0];
    double[] mArrAvgItemAData = new double[0];
    double[] mArrAvgItemVData = new double[0];
    double[] mArrAvgItemDData = new double[0];

    byte[] mRateBytes = new byte[]{0x03, new Integer(0xE8).byteValue()};
    byte[] mPointBytes = new byte[]{0x04, 0x00};
    int mItemCount = 12;

    double sernNumber = 0.02;

    Spinner mRateSpinner;
    Spinner mPointNumberSpinner;

    TextView mGetDataTimeTextView;

    int rateNumber = 1000;
    int time = (int)(256*1000/(2.56*rateNumber));

    public void initAllValue() {
        mEditEffectiveValue = (EditText) findViewById(R.id.effective_value);
        mPeakPeakValue = (EditText) findViewById(R.id.peak_peak_value);
        mPeakPeakValueMM = (EditText)findViewById(R.id.peak_peak_value_mm);
        mPeakValue = (EditText) findViewById(R.id.peak_value);
        spectrum_speed_chart = (RelativeLayout) findViewById(R.id.spectrum_speed_chart);
        spectrum_add_speed_chart = (RelativeLayout) findViewById(R.id.spectrum_add_speed_chart);
        spectrum_drift_chart = (RelativeLayout) findViewById(R.id.spectrum_drift_chart);
        spectrum_speed = (LinearLayout) findViewById(R.id.spectrum_speed);
        spectrum_add_speed = (LinearLayout) findViewById(R.id.spectrum_add_speed);
        spectrum_drift = (LinearLayout) findViewById(R.id.spectrum_drift);
        speed_btn = (RelativeLayout) findViewById(R.id.speed_btn);
        add_speed_btn = (RelativeLayout) findViewById(R.id.add_speed_btn);
        drift_btn = (RelativeLayout) findViewById(R.id.drift_btn);

        mGetDataTimeTextView = (TextView)findViewById(R.id.show_get_data_time);
    }

    public void initButtonAction() {

        speed_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                spectrum_speed.setVisibility(View.VISIBLE);
                spectrum_add_speed.setVisibility(View.GONE);
                spectrum_drift.setVisibility(View.GONE);

                TextView v_circle = (TextView)findViewById(R.id.v_circle);
                v_circle.setBackgroundResource(R.drawable.sei_fill_circle);
                TextView v_text = (TextView)findViewById(R.id.v_text);
                v_text.setTextColor(Color.parseColor("#008fee"));

                TextView d_circle = (TextView)findViewById(R.id.d_circle);
                d_circle.setBackgroundResource(R.drawable.sei_empty_circle);
                TextView d_text = (TextView)findViewById(R.id.d_text);
                d_text.setTextColor(Color.parseColor("#707070"));

                TextView a_circle = (TextView)findViewById(R.id.a_circle);
                a_circle.setBackgroundResource(R.drawable.sei_empty_circle);
                TextView a_text = (TextView)findViewById(R.id.a_text);
                a_text.setTextColor(Color.parseColor("#707070"));
            }
        });

        add_speed_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                spectrum_speed.setVisibility(View.GONE);
                spectrum_add_speed.setVisibility(View.VISIBLE);
                spectrum_drift.setVisibility(View.GONE);

                TextView v_circle = (TextView)findViewById(R.id.v_circle);
                v_circle.setBackgroundResource(R.drawable.sei_empty_circle);
                TextView v_text = (TextView)findViewById(R.id.v_text);
                v_text.setTextColor(Color.parseColor("#707070"));

                TextView d_circle = (TextView)findViewById(R.id.d_circle);
                d_circle.setBackgroundResource(R.drawable.sei_empty_circle);
                TextView d_text = (TextView)findViewById(R.id.d_text);
                d_text.setTextColor(Color.parseColor("#707070"));

                TextView a_circle = (TextView)findViewById(R.id.a_circle);
                a_circle.setBackgroundResource(R.drawable.sei_fill_circle);
                TextView a_text = (TextView)findViewById(R.id.a_text);
                a_text.setTextColor(Color.parseColor("#008fee"));
            }
        });

        drift_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                spectrum_speed.setVisibility(View.GONE);
                spectrum_add_speed.setVisibility(View.GONE);
                spectrum_drift.setVisibility(View.VISIBLE);

                TextView v_circle = (TextView)findViewById(R.id.v_circle);
                v_circle.setBackgroundResource(R.drawable.sei_empty_circle);
                TextView v_text = (TextView)findViewById(R.id.v_text);
                v_text.setTextColor(Color.parseColor("#707070"));

                TextView d_circle = (TextView)findViewById(R.id.d_circle);
                d_circle.setBackgroundResource(R.drawable.sei_fill_circle);
                TextView d_text = (TextView)findViewById(R.id.d_text);
                d_text.setTextColor(Color.parseColor("#008fee"));

                TextView a_circle = (TextView)findViewById(R.id.a_circle);
                a_circle.setBackgroundResource(R.drawable.sei_empty_circle);
                TextView a_text = (TextView)findViewById(R.id.a_text);
                a_text.setTextColor(Color.parseColor("#707070"));
            }
        });
    }
    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(SeismicActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }

        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("测   振");

        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.test_sei_title);

        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isOnMeasureSeismic = false;
                Intent data = new Intent();
                data.putExtra("testValue", mPeakPeakValueMM.getText().toString());
                SeismicActivity.this.setResult(1002, data);

                SeismicActivity.this.finish();
            }
        });


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seismic_activity);
        SysExitUtil.activityList.add(SeismicActivity.this);
        initView();
        initActionBar();
        initAllValue();
        initButtonAction();
        initSpinner();

        if (savedInstanceState == null) {
            mFragment.setContext(SeismicActivity.this);
            mFragment.setTestType("tempTestSeismic");
        }
        sendTestSENRToBlueTooth();
    }
    public void showSERN(byte[] sernData){
        String[] arrData = CommonUtil.bytesToHexStrings(sernData);
//        android.util.Log.e("接受数据====灵敏度：",arrData.);
        String strResult = "";
        for (int i = 0; i < arrData.length; i ++)
        {
            strResult += getCharValueOfSern(arrData[i]);
        }
        sernNumber = Double.parseDouble(strResult);
        android.util.Log.e("最终的数据====灵敏度："+ sernNumber,strResult);
//        int high = Integer.parseInt(arrData[0],16);
//        int low = Integer.parseInt(arrData[1],16);
    }
    public String getCharValueOfSern(String strHex)
    {
        switch (strHex)
        {
            case "30":
                return "0";
            case "31":
                return "1";
            case "32":
                return "2";
            case "33":
                return "3";
            case "34":
                return "4";
            case "35":
                return "5";
            case "36":
                return "6";
            case "37":
                return "7";
            case "38":
                return "8";
            case "39":
                return "9";
            case "2e":
                return ".";
        }
        return "";
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_CAMERA){
            startSeismic();
            return  true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            isOnMeasureSeismic = false;
            Intent data = new Intent();
            data.putExtra("testValue", mPeakPeakValueMM.getText().toString());

            this.setResult(1002, data);
            this.finish();
        }
        return  true;
//        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    public void initView() {
        blindMeasureSeismicAction();
    }


    public void blindMeasureSeismicAction() {
        Button change_spectrum_btn = (Button) findViewById(R.id.measure_seismic);
        change_spectrum_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startSeismic();
            }
        });
    }

    public void sendReviceDataToBlueTooth()
    {
        byte[] dataOK = new byte[]{0x44, 0x41, 0x54, 0x41, 0x6F, 0x6B, 0x23};
        mFragment.sendMessage(dataOK);
    }
    public void sendTestAVDToBlueTooth()
    {
        byte[] sendTestAVD = new byte[]{0x42, 0x46, 0x03, 0x00, 0x00, mRateBytes[0], mRateBytes[1], 0x00, 0x00, mPointBytes[0], mPointBytes[1], 0x23};
        mFragment.sendMessage(sendTestAVD);
        mSendOKDateTime = new Date();
    }
    public void sendTestSENRToBlueTooth()
    {
        byte[] sendTestSENR = new byte[]{0x53, 0x45, 0x4E, 0x52, 0x23};
        mFragment.sendMessage(sendTestSENR);
    }

    public  void startSeismic(){
        isOnMeasureSeismic = !isOnMeasureSeismic;
        String buttonText = isOnMeasureSeismic ? "停止测量" : "开始测量";
        Button change_spectrum_btn = (Button) findViewById(R.id.measure_seismic);

        change_spectrum_btn.setText(buttonText);

        if (isOnMeasureSeismic == true)
        {
            mRateSpinner.setEnabled(false);
            mPointNumberSpinner.setEnabled(false);
            mFragment.mTempTestSeismicDataByte = new byte[0];
            mFragment.mReciveCount = 0;
        }
        else
        {
            mRateSpinner.setEnabled(true);
            mPointNumberSpinner.setEnabled(true);
        }

        sendTestAVDToBlueTooth();

        //查看有没有接受不到蓝牙指令的
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (isOnMeasureSeismic == false)
                {
                    handler.removeCallbacks(this);
                    return;
                }
                int dataOKTime = (int)(256*1000/(2.56*rateNumber));
                if (dataOKTime == time && mSendOKDateTime != null&&new Date().getTime() - mSendOKDateTime.getTime()>=3*time && isOnMeasureSeismic == true)
                {
                    Log.e("new Date().getTime() - mSendOKDateTime.getTime()",(new Date().getTime() - mSendOKDateTime.getTime())+"");

                    if (new Date().getTime() - mSendOKDateTime.getTime() > 3000)
                    {
                        sendTestAVDToBlueTooth();
                    }
                    else
                    {
                        sendReviceDataToBlueTooth();
                    }
                }
                handler.postDelayed(this,100);
            }
        };
        handler.post(runnable);
    }

    public void reviceAVDData()
    {
        if (isOnMeasureSeismic == false)
            return;

        if (mFragment.mReciveCount == mItemCount)
        {
            String[] arrData = CommonUtil.bytesToHexStrings(mFragment.mTempTestSeismicDataByte);
//            EditText originDataShow = (EditText)findViewById(R.id.origin_data_description);
//            originDataShow.setText(Arrays.toString(arrData));
//            Log.e("********测振获取的原始数据*********：",Arrays.toString(arrData));
            double[] arr_seal_data = dealData(arrData);

            dealAllItemDataToAVD(arr_seal_data);
            getAvgValue();

            drawSpectrum(mArrAvgItemDData, R.id.spectrum_drift_chart);
            drawSpectrum(mArrAvgItemAData, R.id.spectrum_add_speed_chart);
            drawSpectrum(mArrAvgItemVData, R.id.spectrum_speed_chart);

            mPeakPeakValue.setText(getPeakPeakValue(mArrAllItemDData));
            mPeakPeakValueMM.setText(getPeakPeakValueMM(mArrAllItemDData));
            mEditEffectiveValue.setText(getEffectiveValue(mArrAllItemVData));
            mPeakValue.setText(getPeakValue(mArrAllItemAData));
            mFragment.mTempTestSeismicDataByte = new byte[0];
            mFragment.mReciveCount = 0;
            Handler mainHandler = new Handler(Looper.getMainLooper());
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    sendTestAVDToBlueTooth();
                }
            },0);

        }
        else {
            time = (int)(256*1000/(2.56*rateNumber));
//            int sendOKTime = time;
            if (mFragment.mReciveCount == 0)
            {
                time = mItemCount*time;
                mGetDataTimeTextView.setText("预估采集测振和获取时间需要"+2*time/1000+"s");
            }

//            Log.e("time",time+"");

            Handler mainHandler = new Handler(Looper.getMainLooper());
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                   sendReviceDataToBlueTooth();
                    mSendOKDateTime = new Date();
                }
            },time);

        }
    }

    public void getAvgValue()
    {
        double sumAData = 0;
        double sumVData = 0;
        double sumDData = 0;
        for (int i = 0; i < mArrAllItemAData.length; i ++)
        {
            sumAData += mArrAllItemAData[i];
            sumVData += mArrAllItemVData[i];
            sumDData += mArrAllItemDData[i];
        }

        double avg_a = sumAData / mArrAllItemAData.length;
        double avg_v = sumVData / mArrAllItemVData.length;
        double avg_d = sumDData / mArrAllItemDData.length;
        mArrAvgItemAData = new double[mArrAllItemAData.length];
        mArrAvgItemVData = new double[mArrAllItemVData.length];
        mArrAvgItemDData = new double[mArrAllItemDData.length];
        for (int i = 0; i < mArrAllItemAData.length; i ++)
        {
            mArrAvgItemAData[i] = mArrAllItemAData[i] - avg_a;
            mArrAvgItemVData[i] = mArrAllItemVData[i] - avg_v;
            mArrAvgItemDData[i] = mArrAllItemDData[i] - avg_d;
        }
    }
    public void dealAllItemDataToAVD(double[] arr_seal_data)
    {
        int m = 0;

        mArrAllItemAData = new double[arr_seal_data.length/3];
        mArrAllItemVData = new double[arr_seal_data.length/3];
        mArrAllItemDData = new double[arr_seal_data.length/3];
        for (int i = 0; i < arr_seal_data.length - 1; i+=3)
        {
            mArrAllItemAData[m] = arr_seal_data[i];
            mArrAllItemVData[m] = arr_seal_data[i+1];
            mArrAllItemDData[m] = arr_seal_data[i+2];
            m++;
        }
    }
    public void dealOneItemDataToAVD(double[] arr_one_data,int count)
    {
        switch (count % 3)
        {
            case 0:
                int m = 0;
                for (int i = 0; i < arr_one_data.length - 1; i+=3)
                {
                    mArrOneTestAData[m] = arr_one_data[i];
                    mArrOneTestVData[m] = arr_one_data[i+1];
                    mArrOneTestDData[m] = arr_one_data[i+2];
                    m++;
                }
                break;
            case 1:
                int n = 0;
                for (int i = 2; i < arr_one_data.length - 2; i+=3)
                {
                    mArrOneTestAData[n] = arr_one_data[i];
                    mArrOneTestVData[n] = arr_one_data[i+1];
                    mArrOneTestDData[n] = arr_one_data[i+2];
                    n++;
                }
                break;
            case 3:
                int k = 0;
                for (int i = 1; i < arr_one_data.length; i+=3)
                {
                    mArrOneTestAData[k] = arr_one_data[i];
                    mArrOneTestVData[k] = arr_one_data[i+1];
                    mArrOneTestDData[k] = arr_one_data[i+2];
                    k++;
                }
                break;
        }
    }
    //画图
    public void drawSpectrum(double[] arr_data, Integer id) {

        LineChartView chart = new LineChartView(SeismicActivity.this);
        RelativeLayout spectrum_speed_chart = (RelativeLayout) findViewById(id);
        List<PointValue> values = new ArrayList<PointValue>();


        DecimalFormat df = new DecimalFormat("######0.00");


        List<AxisValue> xValues = new LinkedList<>();
        double max = arr_data[0];
        for (int i = 0; i < arr_data.length; i++) {
            DecimalFormat dfOne   = new DecimalFormat("######0.0");
            String a = dfOne.format(arr_data[i]);
            float y =  Float.parseFloat(a);
            xValues.add(new AxisValue(i).setLabel(df.format(i/(2.56*rateNumber))));
            values.add(new PointValue(i, y));
            if (Math.abs(max)<Math.abs(arr_data[i]))
            {
                max = arr_data[i];
            }
        }
        List<Line> lines = new ArrayList<Line>();

        if (Math.abs(max) < 0.5)
        {
            List<PointValue> setMaxPointUp = new ArrayList<PointValue>();
            setMaxPointUp.add(new PointValue(0,0.5f));
            List<PointValue> setMaxPointDown = new ArrayList<PointValue>();
            setMaxPointDown.add(new PointValue(0,-0.5f));
            lines.add(new Line(setMaxPointUp).setColor(Color.parseColor("#ff0000")).setCubic(false).setStrokeWidth(1).setPointRadius(0));
            lines.add(new Line(setMaxPointDown).setColor(Color.parseColor("#ff0000")).setCubic(false).setStrokeWidth(1).setPointRadius(0));
        }
        Line line = new Line(values).setColor(Color.parseColor("#008fee")).setCubic(false).setStrokeWidth(1).setPointRadius(0);


        lines.add(line);


        LineChartData data = new LineChartData();
        data.setLines(lines);
        chart.setLineChartData(data);
        Axis axisX = new Axis();//x轴
        axisX.setValues(xValues);
        axisX.setMaxLabelChars(8);
        Axis axisY = new Axis();//y轴

        data.setAxisXBottom(axisX);
        data.setAxisYLeft(axisY);
        spectrum_speed_chart.removeAllViews();
        spectrum_speed_chart.addView(chart);

    }

    //用公式处理数据
    public double[] dealData(String[] arrData) {
        double[] arr_seal_data = new double[arrData.length / 2];
        for (int m = 0; m < arrData.length; m += 2) {
            int low = Integer.parseInt(arrData[m], 16);
            int high = Integer.parseInt(arrData[m + 1], 16);
            double data = ((short) ((getUnsignedInt((high & 0x3f) * 256) + getUnsignedInt(low)) * 4)) / 4.0 / 1638.4;
            arr_seal_data[m / 2] = data/sernNumber;//敏感度
        }
        return arr_seal_data;
    }

    public int getUnsignedInt(int data) {     //将int数据转换为0~4294967295 (0xFFFFFFFF即DWORD)。
        return data & 0x0FFFF;
    }

    public String getEffectiveValue(double[] arr_seal_data) {
        double sqrt_sum = 0;
        for (int i = 0; i < arr_seal_data.length; i++) {
            sqrt_sum += arr_seal_data[i] * arr_seal_data[i];
        }
        double effective_value = Math.sqrt(sqrt_sum / arr_seal_data.length);
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(effective_value);
    }

    public String getPeakPeakValue(double[] arr_seal_data) {
        double sqrt_sum = 0;
        for (int i = 0; i < arr_seal_data.length; i++) {
            sqrt_sum += arr_seal_data[i] * arr_seal_data[i];
        }
        double effective_value = Math.sqrt(sqrt_sum / arr_seal_data.length);
        double peakPeakValue = 2*Math.sqrt(2)*effective_value;
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(peakPeakValue);
    }
    public String getPeakPeakValueMM(double[] arr_seal_data) {
        double sqrt_sum = 0;
        for (int i = 0; i < arr_seal_data.length; i++) {
            sqrt_sum += arr_seal_data[i] * arr_seal_data[i];
        }
        double effective_value = Math.sqrt(sqrt_sum / arr_seal_data.length);
        double peakPeakValue = 2*Math.sqrt(2)*effective_value;
        DecimalFormat df = new DecimalFormat("######0.0000");
        return df.format(peakPeakValue/1000);
    }

    public String getPeakValue(double[] arr_seal_data) {
        double sqrt_sum = 0;
        for (int i = 0; i < arr_seal_data.length; i++) {
            sqrt_sum += arr_seal_data[i] * arr_seal_data[i];
        }
        double effective_value = Math.sqrt(sqrt_sum / arr_seal_data.length);
        double peakValue = Math.sqrt(2)*effective_value;
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(peakValue);
    }

    public Spinner initSpinner(String title, Integer id, ArrayList data) {
        final Spinner spinner = (Spinner) findViewById(id);
        spinner.setPrompt(title);
        spinner.setSelection(0);
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinner.setSelection(position);
                //todo
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinner;
    }

    public void initSpinner() {
        mArrRateList = initRate();
        mRateSpinner = initSpinner("选择频率", R.id.rate_spinner, mArrRateList);
        mRateSpinner.setSelection(3);
        mRateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i)
                {
                    case 0:
                        mRateBytes = new byte[]{0x00, 0x64};
                        rateNumber = 100;
                        break;
                    case 1:
                        mRateBytes = new byte[]{0x00, new Integer(0xC8).byteValue()};
                        rateNumber = 200;
                        break;
                    case 2:
                        mRateBytes = new byte[]{0x01, new Integer(0xF4).byteValue()};
                        rateNumber = 500;
                        break;
                    case 3:
                        mRateBytes = new byte[]{0x03, new Integer(0xE8).byteValue()};
                        rateNumber = 1000;
                        break;
                    case 4:
                        mRateBytes = new byte[]{0x07, new Integer(0xD0).byteValue()};
                        rateNumber = 2000;
                        break;
                    case 5:
                        mRateBytes = new byte[]{0x13, new Integer(0x88).byteValue()};
                        rateNumber = 5000;
                        break;
                    case 6:
                        mRateBytes = new byte[]{0x27, 0x10};
                        rateNumber = 10000;
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        mPointNumber = initPointNumber();
        mPointNumberSpinner = initSpinner("选择采样点", R.id.point_number_spinner, mPointNumber);
        mPointNumberSpinner.setSelection(2);
        mPointNumberSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i)
                {
                    case 0:
                        mPointBytes = new byte[]{0x01, 0x00};
                        mItemCount = 3;
                        break;
                    case 1:
                        mPointBytes = new byte[]{0x02, 0x00};
                        mItemCount = 6;
                        break;
                    case 2:
                        mPointBytes = new byte[]{0x04, 0x00};
                        mItemCount = 12;
                        break;
                    case 3:
                        mPointBytes = new byte[]{0x08, 0x00};
                        mItemCount = 24;
                        break;
                    case 4:
                        mPointBytes = new byte[]{0x10, 0x00};
                        mItemCount = 48;
                        break;
                    case 5:
                        mPointBytes = new byte[]{0x20, 0x00};
                        mItemCount = 96;
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private ArrayList initRate() {
        ArrayList list = new ArrayList<String>();
        list.add("100");
        list.add("200");
        list.add("500");
        list.add("1k");
        list.add("2k");
        list.add("5k");
        list.add("10k");
        return list;
    }
    private ArrayList initPointNumber() {
        ArrayList list = new ArrayList<String>();
        list.add("256");
        list.add("512");
        list.add("1024");
        list.add("2048");
        list.add("4096");
        list.add("8192");
//        list.add("16384");
        return list;
    }


    //采样点为256时，采集1次 *3
    //采样点为512时，采集2次 *3
    //采样点为1024时，采集4次 *3
    //采样点为2048时，采集8次 *3
    //采样点为4096时，采集16次 *3
    //采样点为8192时，采集32次 *3
    //采样点为16384时，采集64次 *3
}